<template>
	<Page class="page-content">
		<el-form slot="page-search" ref="form" :inline="true">
			<el-form-item
				:label="$t('common.belong_merchant') + ':'"
				prop="merchantId"
			>
				<merchant-select v-model="form.merchantId"></merchant-select>
			</el-form-item>
			<el-form-item label="代理账号">
				<el-input
					clearable
					v-model.trim="form.parentProxyName"
					placeholder="请输入"
				/>
			</el-form-item>
			<el-form-item label="会员账号">
				<el-input
					clearable
					v-model.trim="form.userName"
					placeholder="请输入"
				/>
			</el-form-item>
			<el-form-item>
				<el-button
					type="primary"
					icon="el-icon-search"
					:loading="loading"
					:disabled="loading"
					size="medium"
					@click="search"
				>
					{{ $t('common.search') }}
				</el-button>
				<el-button
					icon="el-icon-refresh-left"
					:disabled="loading"
					size="medium"
					@click="reset"
				>
					{{ $t('common.reset') }}
				</el-button>
			</el-form-item>
		</el-form>
		<div class="page-list" slot="page-table" v-if="agentData.id">
			<div class="page-ownpoint">
				<div class="tree-content">
					<CommonProxyTree
						ref="proxyTree"
						:selectedData.sync="selectedData"
						:detailData="agentData"
					/>
				</div>
				<div class="table-content">
					<div
						class="table-items"
						v-if="loading || tableData.length > 0"
					>
						<div
							class="table-item"
							v-for="(itemData, index) in tableData"
							:key="index"
						>
							<Table :data="itemData" :columns="columns" />
						</div>

						<el-pagination
							v-if="total"
							class="pageValue"
							background
							layout="total, sizes,prev, pager, next, jumper"
							:page-size="pageSize"
							:page-sizes="$store.getters.pageSizes"
							:total="total"
							@current-change="handleCurrentChange"
							@size-change="handleSizeChange"
						/>
					</div>
					<el-empty v-else description="暂无数据" />
				</div>
			</div>
		</div>
	</Page>
</template>

<script>
import Page from '@/components/Page'
import list from '@/mixins/list'
import Table from '@/components/Table'
import CommonProxyTree from '@/components/CommonProxyTree/index'
import { TableColumns } from '@/components/TableContainer'
import { Decimal } from 'decimal.js'
let look = false

export default {
	// eslint-disable-next-line vue/name-property-casing
	name: 'ownPoint',
	components: {
		Page,
		Table,
		CommonProxyTree
	},
	mixins: [list],
	data() {
		const customRender = ({ row, column }) => {
			const num = row[column.property]
			return `${Number(num)}%`
		}
		const header = (label) => {
            return <div>{label} <br/> 个人返点比例 </div>
        }
		return {
			selectedData: {
				type: 1,
				userName: undefined,
				id: ''
			},
			agentData: {},
			userType: 1,
			form: {
				userName: undefined,
				merchantId: undefined,
				parentProxyName: undefined
			},
			columns: [
				{
					label: '层级',
					prop: 'proxyLevel',
					customRender: ({ row }) => {
						if (row.userType === 0) {
							return <b>会员</b>
						}
						return row.proxyLevel
					}
				},
				{
					label: '账号',
					prop: 'userName',
					customRender: ({ row }) => {
						// if (row.userType === 0) {
						// 	return (
						// 		<el-link
						// 			type='primary'
						// 			onClick={() => this.vipInfo(row)}
						// 		>
						// 			{row.userName || '-'}
						// 		</el-link>
						// 	)
						// }
						return row.userName || '-'
					}
				},
				TableColumns.ratio({
					header: () => header('德州-俱乐部'),
					prop: 'texasRebate',
					customRender
				}),
				TableColumns.ratio({
					prop: 'texasInsuranceRebate',
					header: () => header('德州-保险'),
					customRender
				}),
				TableColumns.ratio({
					header: () => header('真人'),
					prop: 'actualPersonRebate',
					customRender
				}),
				TableColumns.ratio({
					header: () => header('体育'),
					prop: 'sportsRebate',
					customRender
				}),
				TableColumns.ratio({
					header: () => header('彩票'),
					prop: 'lotteryTicketRebate',
					customRender
				}),
				TableColumns.ratio({
					header: () => header('棋牌'),
					prop: 'chessRebate',
					customRender
				}),
				TableColumns.ratio({
					label: '电竞',
					header: () => header('电竞'),
					prop: 'esportsRebate',
					customRender
				})
			],
			tableData: []
		}
	},
	watch: {
		async selectedData(data) {
			if (look) return
			if (data.type === 1) {
				this.form.parentProxyName = data.userName
				this.form.userName = undefined
			} else {
				if (data.parentProxyName) {
					this.form.parentProxyName = data.parentProxyName
				}
				this.form.userName = data.userName
			}
			this.loadData()
		}
	},
	methods: {
		async queuryAgentInfo() {
			this.agentData = {}
			if (!this.form.parentProxyName) return

			if (this.form.parentProxyName !== this.agentData.proxyName) {
				this.agentData = {}
			}
			try {
				const ret = await this.$api.getProxyDetailQueryDetail({
					userName: this.form.parentProxyName,
					merchantId: this.form.merchantId
				})
				if (ret?.code === 200 && ret.data) {
					const agentData = ret.data

					if (agentData.entryAuthority === 0) {
						this.agentData = {}
						this.$message.error('代理入口权限未开启')
						return
					}

					this.agentData = agentData
					this.agentData['proxyId'] = agentData?.['id']
					this.agentData['proxyName'] = agentData?.['userName']
					return ret.data
				}
			} catch (err) {
				this.agentData = {}
				throw err
			}
		},
		currentTreeItem() {
			if (this.form.userName) {
				this.$refs.proxyTree.setCurrentMember(this.form.userName)
			} else {
				this.$refs.proxyTree.setCurrentProxy(this.form.parentProxyName)
			}
		},
		reset() {
			Object.keys(this.form).forEach((key) => {
				this.form[key] = ''
			})
			this.agentData = {}
		},
		async formatParams() {
			return {
				...this.pageParams,
				merchantId: this.agentData.merchantId,
				...(this.form.userName
					? {
							userName: this.form.userName,
							userType: 0,
							topProxyName: this.form.parentProxyName
					  }
					: {
							parentProxyName: this.form.parentProxyName,
							userType: 1
					  })
			}
		},
		// 处理api
		async loadData() {
			if (Object.keys(this.agentData).length === 0) {
				return
			}
			this.loading = true
			const params = await this.formatParams()
			try {
				const ret = await this.$api.rebateRateMemberList(params)
				if (ret.code === 200 && ret.data && ret.data.record) {
					const { pageNum, pageSize, record = [], totalRecord } =
						ret.data || {}
					this.tableData = record.map(
						({
							proxyRebateRateResp = [],
							memberRebateRateResp = []
						}) => {
							const result = [
								...(proxyRebateRateResp || []),
								...(memberRebateRateResp
									? [memberRebateRateResp]
									: [])
							]

							const common = {
								proxyLevel: '-',
								userName: '-',
								texasRebate: 0,
								actualPersonRebate: 0,
								sportsRebate: 0,
								lotteryTicketRebate: 0,
								texasInsuranceRebate: 0,
								chessRebate: 0,
								esportsRebate: 0
							}

							result.forEach((rebateItem) => {
								if (rebateItem.texasRebate) {
									common.texasRebate = Decimal.add(
										common.texasRebate,
										rebateItem.texasRebate
									)
								}
								if (rebateItem.actualPersonRebate) {
									common.actualPersonRebate = Decimal.add(
										common.actualPersonRebate,
										rebateItem.actualPersonRebate
									)
								}
								if (rebateItem.sportsRebate) {
									common.sportsRebate = Decimal.add(
										common.sportsRebate,
										rebateItem.sportsRebate
									)
								}
								if (rebateItem.lotteryTicketRebate) {
									common.lotteryTicketRebate = Decimal.add(
										common.lotteryTicketRebate,
										rebateItem.lotteryTicketRebate
									)
								}
								if (rebateItem.chessRebate) {
									common.chessRebate = Decimal.add(
										common.chessRebate,
										rebateItem.chessRebate
									)
								}
								if (rebateItem.esportsRebate) {
									common.esportsRebate = Decimal.add(
										common.esportsRebate,
										rebateItem.esportsRebate
									)
								}
								if (rebateItem.texasInsuranceRebate) {
									common.texasInsuranceRebate = Decimal.add(
										common.texasInsuranceRebate,
										rebateItem.texasInsuranceRebate
									)
								}
							})

							return [common, ...result]
						}
					)
					this.total = totalRecord || 0
					this.pageNum = pageNum
					this.ppageSize = pageSize
				}
			} catch (err) {
				throw err
			} finally {
				this.loading = false
			}
		},
		async queryMember() {
			try {
				const res = await this.$api.memberListAPI({
					userName: this.form.userName,
					pageNum: 1,
					pageSize: 1,
					userNameType: '0'
				})

				if (res.code && res.data && res.data.record) {
					const item = res.data.record[0]

					if (!item || Object.keys(item).length === 0) {
						return this.$message.error('会员账号不存在')
					}

					return item
				}
			} catch (err) {
				throw err
			}
		},
		async search() {
			try {
				if (!this.form.parentProxyName && !this.form.userName) {
					this.agentData = {}
					return
				}
				if (!this.form.parentProxyName && this.form.userName) {
					const { parentProxyName } = await this.queryMember()
					this.form.parentProxyName = parentProxyName
				}
				look = true
				await this.queuryAgentInfo()
				await this.loadData()
				setTimeout(() => {
					this.currentTreeItem()
					look = false
				}, 500)
				this.initList()
			} catch (err) {
				throw err
			}
		},

		async vipInfo(row) {
			this.userType = row.userType
			this.form.userName = row.userName
			this.selectedData = row
			setTimeout(() => {
				this.currentTreeItem()
			}, 500)
		}
	}
}
</script>

<style scoped lang="scss">
.page-ownpoint {
	display: flex;
	padding: 10px;
}

.tree-content {
	width: 350px;
	margin-right: 25px;
	max-height: 65vh;
	overflow-y: auto;
	overflow-x: auto;
}
.page-list {
	height: 67vh;
}

.table-item {
	margin-bottom: 20px;
}
.table-content {
	flex: 1;
	display: flex;
	justify-content: center;
	margin-bottom: 150px;
	overflow: auto;
}
.table-items {
	flex: 1;
	max-height: 65vh;
	overflow-y: auto;
	overflow-x: auto;
}
::v-deep .game-container .content {
	padding: 0;
}
.snap-form-item {
	::v-deep .input .el-input__inner {
		border-top-left-radius: 0;
		border-bottom-left-radius: 0;
		margin-left: -4px;
	}
	::v-deep .el-select .el-input__inner {
		border-top-right-radius: 0;
		border-bottom-right-radius: 0;
		border-right: none;
	}
}
</style>
